// app.js
const mqttClient = require('./utils/mqtt-client.js')
const deviceManager = require('./utils/device-manager.js')
App({
  onLaunch() {
    // 初始化云开发
    // if (wx.cloud) {
    //   wx.cloud.init({
    //     env: 'your-cloud-env-id',
    //     traceUser: true
    //   })
    // }
    
    // // 检查登录状态
    // this.checkLoginStatus()
    //  // 连接 OneNET MQTT
    //  this.connectToOneNET()
    // 初始化设备管理器
    //this.initDeviceManager()
  },
  // 连接 OneNET
  async connectToOneNET() {
    try {
      console.log('正在连接 OneNET MQTT...')
      await mqttClient.connect()
      console.log('OneNET MQTT 连接成功')
    } catch (error) {
      console.error('OneNET MQTT 连接失败:', error)
      // 可以在这里添加重连逻辑或用户提示
    }
  },
  // 设备状态变化事件
  emitDeviceStatusChange(deviceId, status) {
    const pages = getCurrentPages()
    pages.forEach(page => {
      if (page.onDeviceStatusChange) {
        page.onDeviceStatusChange(deviceId, status)
      }
    })
  },

  // 连接状态变化事件
  emitConnectionStateChange(connected, error) {
    const pages = getCurrentPages()
    pages.forEach(page => {
      if (page.onConnectionStateChange) {
        page.onConnectionStateChange(connected, error)
      }
    })
  },

  globalData: {
    userInfo: null,
    deviceList: [],
    roomList: [],
    sceneList: [],
    mqttClient: mqttClient,
    deviceManager: deviceManager,
    connectionStatus: {
      connected: false,
      lastUpdate: null
    }
  },
  
  // 检查登录状态
  checkLoginStatus() {
    const token = wx.getStorageSync('token')
    if (token) {
      // 验证token有效性
      this.verifyToken(token)
    } else {
      // 跳转到登录页或使用游客模式
      this.guestMode()
    }
  },
  
  
  // 更新设备状态
  updateDeviceStatus(deviceId, status) {
    const devices = this.globalData.deviceList
    const device = devices.find(d => d.id === deviceId)
    if (device) {
      device.status = status
      this.globalData.deviceList = devices
      wx.setStorageSync('deviceList', devices)
      
      // 发送状态更新事件
      this.emitDeviceStatusChange(deviceId, status)
    }
  },
  
  // 发送设备状态变化事件
  emitDeviceStatusChange(deviceId, status) {
    const pages = getCurrentPages()
    pages.forEach(page => {
      if (page.onDeviceStatusChange) {
        page.onDeviceStatusChange(deviceId, status)
      }
    })
  }
})